package org.example.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author limeng
 * @create 2021-06-04 17:09
 */
@RestController
public class TestController {

    private final static Logger logger = LoggerFactory.getLogger(TestController.class);

    @GetMapping("/test")
    @SentinelResource(value = "test11", blockHandler = "blockHandlerMethod",fallback = "fallbackMethod")
    public String test(@RequestParam("id") Integer id) {
        logger.info("ok");
        if (id < 0) {
            throw new RuntimeException("id无效");
        }
        return "ok";
    }

    public String blockHandlerMethod(Integer id, BlockException e) {
        if (e instanceof FlowException) {
            return "当前请求过于火爆，您已被流控";
        }
        if (e instanceof DegradeException) {
            return "当前请求过于火爆，您已被降级";
        }
        if (e instanceof ParamFlowException) {
            return "当前请求过于火爆，您已被热点参数限流";
        }
        return "服务器火爆，请稍后再试";
    }

    public String fallbackMethod(Integer id){
        return "默认服务器出错了";
    }

    @GetMapping("/test2")
    public String test2() {
        logger.info("test2");
        return "test2";
    }
}
